
/**
 * Namespace    Classes.Service
 * Class        CustomerService
 * Author       Bram Vandenbussche
 * Description  Provides service level and access level logic for OrderState objects
 * Version      1.0
**/

var CustomerService = new function() {

	var root = this;
	
	this.Customers = null;
	this.SavedFileName = "customers.xml";
	
	
	this.LoadCustomers = function() {
		this.Customers = [];
        
        var xml = LoadXmlFromFile(this.SavedFileName);
        
        if (xml != undefined) {
			air.trace("CustomerService: File found! Loading file xml");
            // if there is, load the settings from it
            this.LoadCustomersFromFile(xml);
            
            // Render orders
            this.RenderCustomers();
        } else {
			air.trace("CustomerService: File not found! Loading from WS");
            // if there isn't, create the default settings
            this.LoadCustomersFromWS(root.SaveAndRender);
        }
	}
	
	
	this.LoadCustomersFromFile = function(xml) {
		$.each($("customer", xml), function() {
            var c = new Customer();
            
            // Setting aanmaken vanuit xml
            c.Deserialize($(this));
            
            // Setting opslaan
            root.AddCustomer(c);
        });
	}
	
	
	this.LoadCustomersFromWS = function(callback) {
		var getCustomersUrl = PrestashopService.PS_MOBILE_AUTHORIZATION.api.customers["xlink:href"] + "?display=full";
		
		var getCustomersArgs = {
			url: getCustomersUrl,
			method: 'GET',
			dataType: "xml",
			async: false,
			beforeSend: function(jqXHR, settings) {            
				// Authentication
				PrestashopService.PrepareAjaxCredentials(jqXHR);
				
				// Status instellen
				SetStatus("loading");
			},
			success: function(data, textStatus, jqXHR) {
                air.trace("CustomerService: received response from WS");
                
				// Return data omvormen naar JSON
				var PS_MOBILE_CUSTOMER_LIST = $.xml2json(data);
				
				// Response data cachen
				root.AssembleFromJson(PS_MOBILE_CUSTOMER_LIST.customers.customer);
				
				callback();
			}
		}
		
		$.ajax(getCustomersArgs);
	}
	
	
	this.AssembleFromJson = function(sourceList) {
		if (sourceList.length == undefined) {
			var c = new Customer();
				
			c.AssembleFromJson(sourceList);
			
			root.AddCustomer(c);
		} else {
			for (var i in sourceList) {
				var c = new Customer();
				
				c.AssembleFromJson(sourceList[i]);
				
				root.AddCustomer(c);
			}
		}
    }
	
	
	this.SaveAndRender = function() {
		// save them
        root.PersistCustomers();
        
        // and display them
        root.RenderCustomers();
	}
	
	
	this.PersistCustomers = function() {
		air.trace("CustomerService: Persisting customers to file");
        
        var xml = SerializeList(root.Customers, "customers");
        
        SaveXmlToFile(xml, this.SavedFileName);
	}
	
	
	this.AddCustomer = function(customer) {
		root.Customers[customer.ID] = customer;
	}
	
	
	this.GetByID = function(id) {
		// Indien er nog geen klanten zijn opgehaald, dan doen we dat eerst
		if (this.Customers == undefined) {
            this.LoadCustomers();
        }
		
		var foundCustomer = null;
    
		// Eerst proberen we de klant te zoeken in de cache
		foundCustomer = root.Customers[id];
		
		// Als dat niet lukt, gaan we zoeken in de WS
		if (foundCustomer == undefined) {
			var getCustomerByIdUrl = PrestashopService.PS_MOBILE_AUTHORIZATION.api.customers["xlink:href"] + "/" + id;
			
			var getCustomerByIdArgs = {
				url: getCustomerByIdUrl,
				method: 'GET',
				dataType: 'xml',
				async: false,
				beforeSend: function(jqXHR, settings) {            
					// Authentication
					PrestashopService.PrepareAjaxCredentials(jqXHR);
					
					// Status instellen
					SetStatus("loading");
				},
				success: function(data, textStatus, jqXHR) {
					foundCustomer = new Customer();
					
					foundCustomer.AssembleFromJson($.xml2json(data).customer);
				}
			}
		
			$.ajax(getCustomerByIdArgs);
		}
		
		return foundCustomer;
	}
	
	
	this.RenderCustomers = function() {
		if (this.Customers == undefined) {
            this.LoadCustomers();
        } else {
        
            // Tab header aanpassen met aantal
            $("#customer_count").html("(" + this.Customers.length + ")");
            
            // Tab renderen
            CustomersListView.RenderView();
        }
	}
	
	
	this.ClearCustomers = function() {
		root.Customers = null;
	}
	
	this.ClearCache = function() {
		// Clear ordersfile
		DeleteFile(root.SavedFileName);
		
		// Clear orders in memory
		root.ClearCustomers();
		
		// Reload customers
		root.LoadCustomers();
	}
}